const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const indexRouter = require('./routes/web/index');
const authRouter = require('./routes/web/auth');
// 导入 account 路由接口文件
const planRouter = require('./routes/api/plan');
const authApiRouter = require('./routes/api/auth');
const session = require('express-session')
const MongoStore = require('connect-mongo')
// 导入数据库配置项
const { DBHOST, DBPORT, DBNAME } = require('./config/config')

const app = express();
app.use(session({
  name: 'sid',
  secret: 'wang',
  saveUninitialized: false,
  resave: true,
  store: MongoStore.create({
    mongoUrl: `mongodb://${DBHOST}:${DBPORT}/${DBNAME}`
  }),
  cookie: {
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24 * 7
  }
}))

// view engine setup
app.set('html', path.join(__dirname, 'html'));
app.set('view engine', 'html');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/', authRouter);
app.use('/api', planRouter);
app.use('/api', authApiRouter);

app.use(function (req, res, next) {
  res.render('404')
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
